import { RouteRecordRaw, createRouter, createWebHashHistory } from "vue-router"
import Cookies from 'js-cookie'
import { GetMenuTreeRes, getMenuTree } from "@/api/security";
import { SysMenuTree } from "@/interface/user";
import { useMenuStore } from "@/store/menuStore";
import emitter from "@/utils/emitter";

const modules = import.meta.glob('@/views/**/*.vue')
// const ROUTE_PREFIX = '/index'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: '/',
    redirect: '/index',
    component: () => import('../views/navbar/index.vue'),
    children: [
      {
        path: 'index',
        name: '首页',
        component: () => import('../views/home/index.vue')
      },
      {
        path: 'profile',
        name: '个人中心',
        component: () => import('../views/profile/index.vue')
      },
      {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('../components/Exception/404.vue')
      },
      {
        path: 'forbidden',
        name: 'forbidden',
        component: () => import('../components/Exception/403.vue')
      }
    ]
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('../views/login/index.vue'),
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, _from, next) => {
  if (to.path == '/login') {
    next()
  } else {
    const accessToken = Cookies.get('accessToken')
    if (accessToken && accessToken != '') {
      if (!useMenuStore().isLoading) {
        useMenuStore().isLoading = true
        //加载异步路由-已经在navbar里面加载
        // renderAsyncRouter()
        //保证路由已经被加入
        next({ ...to, replace: true })
      } else {
        next()
      }
    } else {
      window.$message.error('请先登录')
      next('/login')
    }
  }
})

router.afterEach((to, _from, _failure) => {
  //切换面包屑
  emitter.emit("refreshBreadcrumb", to.path as string);
  //切换动态标签
  useMenuStore().toggleDynamicTag(to.path as string)
  //保存当前活跃的路由path
  useMenuStore().selectedKeys[0] = to.path as string
})

//退出登录时候，用记忆之前的路由清空
let recordRoute: any[] = []

const renderAsyncRouterInner = async (reload: boolean = false) => {
  // 动态路由
  let ouputRoute: any = []
  if (useMenuStore().menuList.length == 0 || reload) {
    recordRoute = []
    const { data: res }: { data: GetMenuTreeRes<SysMenuTree[]> } = await getMenuTree() as any
    res.data.forEach((menu: SysMenuTree) => {
      recordRoute.push(menu.menuName)
      ouputRoute.push(dfs(menu, menu.path || ''))
    })
    //固定路由
    if (useMenuStore().fixedMenuList.length == 0) {
      useMenuStore().setFixedMenuList(router.getRoutes() as any)
    }
    //异步路由
    useMenuStore().setMenuList(ouputRoute)
  } else {
    ouputRoute = useMenuStore().menuList
  }
  return ouputRoute
}

export const renderAsyncRouter = (callback?: Function, reload: boolean = false) => {
  renderAsyncRouterInner(reload).then((arr: any) => {
    arr.forEach((menu: any) => {
      router.addRoute('/', menu)
    })
    callback && callback()
  }).catch(err => {
    console.log(err);
  })
}

//重置路由
export const resetRoute = () => {
  for (let routeName of recordRoute) {
    router.removeRoute(routeName)
  }
}

const dfs = (data: SysMenuTree, prePath: string) => {
  const curRoute: Record<string, any> = {}
  curRoute.path = data.path
  curRoute.name = data.menuName
  curRoute.meta = { icon: data.icon }
  curRoute.children = []
  curRoute.component = loadView(data.component || '')
  //路径对应名称
  useMenuStore().pathToName[prePath] = data.menuName
  if (data.children && data.children.length > 0) {
    data.children.forEach(menu => {
      curRoute.children.push(dfs(menu, prePath + '/' + menu.path))
    })
  } else {
    delete curRoute['children']
  }
  if (curRoute.component === undefined) {
    delete curRoute.component
  }
  return curRoute
}

const loadView = (view: string) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = modules[path];
    }
  }
  return res;
}
export default router